import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import * as apiServer from 'api/list'

import Button from 'components/Button'

import forms from './forms'

import './style.less'

function Detail(props) {
  const [value, setValue] = useState({})
  const urlParams = useParams()
  const isEdit = urlParams.status === 'edit'
  const title = isEdit ? '编辑用户' : '新建用户'

  const onSubmit = () => {
    if (value.id) {
      apiServer.putUser(value).then(() => {
        props.history.go(-1)
      })
    } else {
      apiServer.addUser(value).then(() => {
        props.history.go(-1)
      })
    }
  }

  useEffect(() => {
    if (isEdit) {
      apiServer.getUserById(urlParams.id).then((res) => {
        setValue(res.data.data)
      })
    }
  }, [isEdit, urlParams.id])

  const mapComponents = ({ name, type, label }) => {
    switch (type) {
      case 'Input':
      default:
        return (
          <li key={name}>
            <label htmlFor={name}>{label}*</label>
            <input
              type="text"
              id={name}
              value={value[name] || ''}
              onChange={(e) => {
                e.persist()
                setValue((state) => ({ ...state, [name]: e.target.value }))
              }}
            />
          </li>
        )
    }
  }

  return (
    <div className="container">
      <div className="title">{title}</div>
      <ul>
        {forms.map(mapComponents)}
        <li style={{ paddingLeft: 95 }}>
          <Button style={{ marginRight: 15 }} onClick={onSubmit}>
            提交
          </Button>
          <Button type="secondary" onClick={() => props.history.go(-1)}>
            取消
          </Button>
        </li>
      </ul>
    </div>
  )
}

export default Detail
